<template>
  <van-button
    :icon="value === 1 ? 'good-job' : 'good-job-o'"
    :class="{ liked: value === 1 }"
    :loading="loading"
    @click="onCollect"
  />
</template>

<script>
// 加载文章点赞请求的方法
import { addLike, deleteLike } from '@/api/article'
export default {
  name: 'LikeArticle',
  props: {
    value: {
      type: Number,
      required: true
    },
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data() {
    return {
      loading: false
    }
  },
  methods: {
    async onCollect() {
      // 加载loading
      this.loading = true
      try {
        let status = -1
        if (this.value === 1) {
          // 已点赞,取消点赞
          await deleteLike(this.articleId)
        } else {
          // 没点赞,添加点赞
          await addLike(this.articleId)
          status = 1
        }
        // 更新点赞状态
        this.$emit('input', status)
        // 点赞提示
        this.$toast.success(status === 1 ? '点赞成功' : '取消点赞')
      } catch (err) {
        this.$toast.fail('加载失败')
      }
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
.liked {
  .van-icon {
    color: #e5645f;
  }
}
</style>